import React from "react";
import {
    Input,
    InputGroup,
    InputLeftAddon,
    Button,
    FormControl,
    Checkbox,
    Link,
    Text,
    Flex,
    Divider,
    Box,
    useToast,
} from "@chakra-ui/react";
import { MdPerson, MdLock } from "react-icons/md";
import { FaWeibo, FaWeixin, FaQq } from "react-icons/fa";
import { useFormik } from 'formik'

export default function SignIn() {
    const toast = useToast()
    const formik = useFormik({
        initialValues: {},
        validate: values => {
            const errors = {}
            if (!values.email) {
                errors.email = '请输入手机号或邮箱'
            } else if (values.email.length > 20) {
                errors.email = '手机号或邮箱的长度不能大于20'
            }
            if (!values.password) {
                errors.password = '请输入密码'
            } else if (values.password.length < 8) {
                errors.password = '密码的长度不能小于8'
            }
            return errors
        },
        onSubmit: values => {
            console.log('==values', values)
            fetch('https://conduit.productionready.io/api/users/login', {
                method: 'POST',
                headers: {
                    'content-type': 'application/json'
                },
                mode: 'cors',
                body: JSON.stringify({ user: values })
            }).then(function (response) {
                response.json().then((res) => {
                    console.log('==res', res)
                    // res = {
                    //     "user": {
                    //         "id": 167299,
                    //         "email": "yang8787jie@126.com",
                    //         "createdAt": "2021-05-04T11:56:30.844Z",
                    //         "updatedAt": "2021-05-04T11:56:30.850Z",
                    //         "username": "yang8787jie",
                    //         "bio": null,
                    //         "image": null,
                    //         "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTY3Mjk5LCJ1c2VybmFtZSI6Inlhbmc4Nzg3amllIiwiZXhwIjoxNjI1MzEzODAxfQ.ZTgUnBrT1bnkpdmwXRWdtptexQv-tJtMLL2FgzMBPbE"
                    //     }
                    // };
                    if (res.errors) {
                        let errorArr = [];
                        for (let [key, values] of Object.entries(res.errors)) {
                            for (let value of values) {
                                errorArr.push(`${key} ${value}`);
                            }
                        }
                        toast({
                            title: errorArr.join(','),
                            position: 'top',
                            status: 'error',
                            isClosable: false,
                        })
                        return;
                    }
                    if (res.user) {
                        toast({
                            title: `${res.user.username}登录成功`,
                            position: 'top',
                            status: 'success',
                            isClosable: false,
                        })
                    }
                })
            })
        }
    })
    return (
        <form onSubmit={formik.handleSubmit}>
            <Box
                bgColor="hsla(0,0%,71%,.1)"
                borderWidth="1px"
                borderStyle="solid"
                borderColor="brand.border"
                borderRadius="4px 4px 4px 4px"
            >
                <FormControl
                    isDisabled={false}
                    isInvalid={false}
                >
                    <InputGroup borderColor="transparent">
                        <InputLeftAddon
                            children={<MdPerson />}
                            fontSize={20}
                            bgColor="transparent"
                            color="brand.sub"
                            px={2}
                        />
                        <Input
                            placeholder="手机号或邮箱"
                            _focus={{ border: 'none' }}
                            _hover={{ border: 'none' }}
                            border="none"
                            pl={1}
                            name="email"
                            value={formik.values.email}
                            onChange={formik.handleChange}
                            onBlur={formik.handleBlur}
                        />
                    </InputGroup>
                    <Text
                        color="#e53e3e"
                        textAlign="left"
                        pl="42"
                    >
                        {formik.touched.email && formik.errors.email ? formik.errors.email : null}
                    </Text>
                </FormControl>
                <Divider borderColor="brand.border" />
                <InputGroup borderColor="transparent">
                    <InputLeftAddon
                        children={<MdLock />}
                        fontSize={20}
                        bgColor="transparent"
                        color="brand.sub"
                        px={2}
                    />
                    <Input
                        type="password"
                        placeholder="密码"
                        _focus={{ border: 'none' }}
                        _hover={{ border: 'none' }}
                        border="none"
                        pl={1}
                        name="password"
                        value={formik.values.password}
                        onChange={formik.handleChange}
                        onBlur={formik.handleBlur}
                    />
                </InputGroup>
                <Text
                    color="#e53e3e"
                    textAlign="left"
                    pl="42"
                >
                    {formik.touched.password && formik.errors.password ? formik.errors.password : null}
                </Text>
            </Box>
            <Flex
                justifyContent="space-between"
                color="brand.sub"
                mt={3}
            >
                <Checkbox defaultIsChecked size="sm">记住我</Checkbox>
                <Link href="#" isExternal fontSize={14}>登录遇到问题?</Link>
            </Flex>
            <Button
                _hover={{ bgColor: "#1767A8" }}
                w="100%"
                colorScheme="teal"
                bgColor="#3194d0"
                borderRadius="25px"
                mt={3}
                type="submit"
            >登录</Button>
            <Flex
                alignItems="center"
                justifyContent="space-evenly"
                px={6}
                pt={42}
            >
                <Divider />
                <Text
                    whiteSpace="nowrap"
                    px={4}
                    fontSize={12}
                    color="#b5b5b5"
                    fontWeight={500}
                >社交帐号登录</Text>
                <Divider />
            </Flex>
            <Flex
                justifyContent="space-evenly"
                fontSize={28}
                pt={2}
            >
                <FaWeibo color="#e05244" />
                <FaWeixin color="#00bb29" />
                <FaQq color="#498ad5" />
            </Flex>
        </form>
    );
}
